package com.fauks.restful;

import com.fauks.restful.bean.ApiResult;
import com.fauks.restful.bean.ApiUser;
import com.fauks.restful.utils.EasyGsonUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        //objToJson();
        //arrayToJson();

        //jsonToObj();
        //jsonToArray();
        //String string[] = {"1", "2"};
        StringBuilder sb = new StringBuilder();
        sb.append("a").append(",").append("b").append(",");
        System.out.println(sb.deleteCharAt(sb.length() - 1));
        jsonToArray();
    }

    private static void jsonToArray() {
        String str = "{\"code\":1,\"message\":\"success\",\"data\":[{\"username\":\"1\",\"password\":\"fauks\"},{\"username\":\"2\",\"password\":\"bob\"},{\"username\":\"3\",\"password\":\"jay\"}]}";
        ApiResult<List<ApiUser>> res = EasyGsonUtils.fromJson(str, new TypeToken<ApiResult<List<ApiUser>>>() {
        });
        jsonToObj();
        System.out.println(res);
    }

    private static void jsonToObj() {
        String str = "{\"code\":1,\"message\":\"success\",\"data\":{\"username\":\"fauks\",\"password\":\"12\"}}";
        ApiResult<ApiUser> res = EasyGsonUtils.fromJson(str, new TypeToken<ApiResult<ApiUser>>() {
        });
        System.out.println(res);
    }

    //{"code":1,"message":"success","data":[{"username":"1","password":"fauks"},{"username":"2","password":"bob"},{"username":"3","password":"jay"}]}
    private static void arrayToJson() {
        ApiResult<List<ApiUser>> user = new ApiResult<>();
        user.code = 1;
        user.message = "success";

        List<ApiUser> apiUserList = new ArrayList<>();
        /*apiUserList.add(new ApiUser("1", "fauks"));
        apiUserList.add(new ApiUser("2", "bob"));
        apiUserList.add(new ApiUser("3", "jay"));*/
        user.data = apiUserList;

        String s = new Gson().toJson(user);
        System.out.println(s);
    }

    // {"code":1,"message":"success","data":{"username":"fauks","password":"12"}}
    private static void objToJson() {
        ApiResult<ApiUser> user = new ApiResult<>();
        user.code = 1;
        user.message = "success";
        ApiUser apiUser = new ApiUser();
        apiUser.password = "12";
        apiUser.username = "fauks";
        user.data = apiUser;

        String s = new Gson().toJson(user);
        System.out.println(s);
    }
}
